# coding:utf-8

"""获取 request 等"""

from django.http import HttpResponse as djangoHttpResponse
import json
from mako.lookup import TemplateLookup

# request = []
#
# def setrequest(req):
#     request.append(req)
#
# def getrequest():
#     return request[0]
#


def convert_to_builtin_type(obj):
    """
    有字典属性直接返回实例的字典
    可迭代的实例所有内部实例取字典
    """

    import types
    if type(obj) is types.DictType:

        # 对字典内所有值迭代
        d = {}
        for key in obj.keys():
            d.update({key:convert_to_builtin_type(obj.get(key))})
        return d
    if hasattr(obj, '__dict__'):
        return convert_to_builtin_type(obj.__dict__)

    if hasattr(obj, '__iter__'):
        return [convert_to_builtin_type(i) for i in obj]
    if type(obj) is types.UnicodeType:
        return obj
    # from datetime import datetime, date
    # if isinstance(obj, datetime) or isinstance(obj, date):
    #     obj = str(obj)
    return str(obj)


def HttpResponse(odj):
    return djangoHttpResponse(json.dumps(convert_to_builtin_type(odj)))



from django.shortcuts import render
# from django.http import HttpResponse
import json
# from djangomako.shortcuts import render_to_response
from mako.template import Template
from  django import template

# from django.shortcuts import render_to_response
import os

def hello(request):
    # return djangoHttpResponse('hello')
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    BASE_DIR = os.path.dirname(BASE_DIR)
    mytemplate = Template(filename=BASE_DIR + r'\hello.html')
    print (mytemplate.render(name='mm', req=request))

    return djangoHttpResponse(mytemplate.render(name='mm', req=request))


def mako_render(request,template_name,dict):
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    BASE_DIR = os.path.dirname(BASE_DIR)
    app_dir = template_name.split('/')[1]
    app_dir = ''
    BASE_DIR = BASE_DIR + "\\WebBase" + app_dir + "\\templates"
    #content = render(request,BASE_DIR + template_name)
    mylookup = TemplateLookup(directories=[BASE_DIR])
    # mytemplate = Template(filename=BASE_DIR + template_name, lookup=mylookup)
    mytemplate = mylookup.get_template(template_name)

    dict["request"] = request
    template_str = mytemplate.render(**dict)
    # print template_str
    return djangoHttpResponse(template_str)


if __name__ == '__main__':
    mako_render(None, "/cm/cgk.html",{})
